import { getShops } from "@src/api/catering";
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import location from "@src/store/location";
import router from "@src/router";

Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: location,
    fields: ['latitude', 'longitude'],
    actions: ['getLocation']
  }],
  data: {
    curShopId: null,
    inputData: null,
    searchList: [],
    shopList: [],
  },
  methods: {
    onLoad(options) {
      let { shopId } = options;
      this.setData({ curShopId: shopId ? Number(shopId) : null });
      if (!this.data.latitude) {
        this.getLocation().then(res => {
          this.fetchData(res.latitude, res.longitude);
        }).catch(() => {
          this.fetchData();
        })
      } else {
        this.fetchData(this.data.latitude, this.data.longitude);
      }
    },
    onPullDownRefresh() {
      this.getLocation().then(res => {
        this.fetchData(res.latitude, res.longitude);
      }).catch(() => {
        this.fetchData();
      })
      wx.stopPullDownRefresh();
    },
    fetchData(latitude, longitude) {
      let data = {};
      if (latitude) {
        data.latitude = latitude;
        data.longitude = longitude;
      }
      getShops(data).then(res => {
        if (res.code === 0) {
          this.setData({
            shopList: res.data,
            searchList: res.data
          })
          this.shopList = res.data;
        }
      })
    },
    handleSearch(e) {
      let searchList = [];
      let value = e.detail.value;
      this.data.shopList.forEach(v => {
        if (v.shopName.indexOf(value) > 0) {
          searchList.push(v);
        }
      })
      console.log("searchList", searchList)
      if (value) {
        this.setData({
          inputData: value
        })
      }
      this.setData({ searchList: searchList })
    },
    handleClearInput() {
      this.setData({ inputData: "" })
    },
    // 选择门店
    chooseShop(e) {
      let item = e.currentTarget.dataset.item;
      if (!item.isOpenTime) {
        wx.showToast({ title: "该门店已打烊", icon: "none", duration: 1000 });
        return;
      }
      if (item.distance <= 10 * 1000) {
        this.changeShop(item.shopId);
      } else {
        // 如果门店距离超过10km
        wx.showModal({
          title: "温馨提示",
          content: "当前位置离门店较远，是否继续？",
          success: (res) => {
            if (res.confirm) {
              this.changeShop(item.shopId);
            }
          }
        });
      }
    },
    changeShop(shopId) {
      const eventChannel = this.getOpenerEventChannel()
      if (eventChannel && eventChannel.emit) {
        eventChannel.emit('change', shopId);
      }
      router.back()
    }
  }
})
